<template>
    <view>

        <view class="page-section-scroll-view body-space-l guoshao-view">
            <view class="cu-bar solid-bottom">
                <view class="action">
                    <text class="cuIcon-title text-blue"></text>
                    素材类型
                </view>
            </view>

            <view class="container">
                <view class="body">
                    <view class="page-section page-section-space guoshao-radio">
                        <radio-group @change="redioChange">
                            <view class="ttui-cell__hd">
                                <view class="guoshao-view-radio" v-for="(item,index) in ritems" :key="index">
                                    <radio :value="item.id" :checked="item.checked" :disabled="false" :data-classtype="item.classType" @click="radioClick" color="#5571DD" />
                                    <text>{{ item.name }}</text>
                                </view>
                            </view>
                        </radio-group>
                    </view>
                </view>
            </view>

            <view class="guoshao-upload">
                <view class="cu-bar bg-white margin-top">
                    <view class="action">打开相册，选择素材上传</view>
                    <view class="action">
                        <block v-if="classType == 2">{{ videoCount }}/1</block>
                        <block v-if="classType != 2">{{ imgList.length }}/{{ optionCount }}</block>
                    </view>
                </view>
                <view class="cu-form-group">
                    <view class="grid col-4 grid-square flex-sub">
                        <view class="bg-img" v-if="classType == 2 && videoSrc" >
                            <video :src="videoSrc" :controls="true" style="width: 80px; height: 80px"></video>
                            <view class="cu-tag bg-red" @click="myDelVideo">
                                <text class="cuIcon-close"></text>
                            </view>
                        </view>

                        <view  class="bg-img"
                            v-for-item="item"
							v-for="(item,index) in imgList"
                            :key="index"
                            @click="myViewImage"
                            :data-url="imgList[index].path"
                            v-if="classType != 2"  > 
                            <image :src="imgList[index].path" mode="aspectFill"></image>
                            <view class="cu-tag bg-red" @click.stop.prevent="myDelImg" :data-index="index">
                                <text class="cuIcon-close"></text>
                            </view>
                        </view>

                        <block v-if="classType == 2">
                            <view class="solids" @click.stop.prevent="myChooseVideo" v-if="!videoSrc">
                                <text class="cuIcon-cameraadd"></text>
                            </view>
                        </block>
                        <block v-if="classType != 2">
                            <view class="solids" @click.stop.prevent="myChooseImage" v-if="imgList.length < optionCount">
                                <text class="cuIcon-cameraadd"></text>
                            </view>
                        </block>
                    </view>
                </view>
                <view class="guoshao-tishi">
                    <text class="text-gray">提示：仅支持JPEG、PNG、JPG格式，单个素材不能超过10M，一次最多选9个。上传不合理的图片时会审核不通过</text>
                    <text class="text-gray" v-if="uploadCount > 0" style="color: red">每日上传限额{{ uploadCount }}个，目前已上传{{ uploadedQuantity }}个。</text>
                </view>
            </view>

			<view class="cu-bar solid-bottom">
				<view class='action'>
					<text class='cuIcon-title text-blue'></text>标签
				</view>
			</view>
			<view class="line" v-for="(item,index) in items" :key="index">
				<jiuaiCheckbox @change="changeBox" :borderStyle="item.checked ? '1px solid #5571DD' : '1px solid #d1d1d1'" :value="item.id" :data-id="item.id"></jiuaiCheckbox>
				<text>{{item.label}}</text>
			</view>
        </view>

        <view class="guoshao-tishi">
            <text class="text-gray">
                提示：您所上传的图片受云平台以及抖音内容管理规范约束，我们将通过技术/人工方式实施内容审查，但任无法保证完全的合规性， 请创作者严格自查图片的合规性。
            </text>
        </view>

        <view class="padding flex flex-direction">
            <button class="cu-btn bg-blue margin-tb-sm lg guoshao-button" @click.stop.prevent="uploadImg" v-if="classType != 2">上传素材</button>
            <button class="cu-btn bg-blue margin-tb-sm lg guoshao-button" @click.stop.prevent="uploadVideo" v-if="classType == 2">上传素材</button>
        </view>
		
		
		
    </view>
</template>

<script>
// d:\applet\byteApplet\dy-wallpaper-applet-2\pages\creator\upload\upload.js
const Rest = require('../../../utils/rest');

const http = require('../../../utils/http.js');

const Constants = require('../../../utils/constants.js');

const Config = require('../../../utils/config.js');


import jiuaiCheckbox from "@/components/jiuai-checkbox/jiuai-checkbox.vue";

export default {
	components:{
		jiuaiCheckbox
	},
    data() {
        return {
            access_token: '',
            uploadedQuantity: 0,
            //用户已上传数量
            uploadCount: 0,
            //每日上传数量
            optionCount: 9,
            //可选择数量
            classId: '',
            imgList: [],
            items: [],
            ritems: [],
            tags: '',
			tagsIds:'',
            isUpload: false,
            maxByte: 1024 * 1024 * 10,
			maxByteVideo: 1024 * 1024 * 20,
            //最大上传
            classType: 1,
            videoSrc: {},
            videoCount: 0
			                
        };
    },
    onLoad: function (options) {
        this.getBasicsData();
        this.setData({
        });
		
    },
	
    methods: {
		changeBox(e){//选中切换事件(由组件发起)
		
			let id = e.detail.value; 
			let checked = e.detail.checked; 
			
			var items = this.items;
			for (var i = 0, lenI = items.length; i < lenI; ++i) {
			    if (items[i].id == id) {
					items[i].checked = checked;
					break;
			    }
			}
			
			this.setData({
			    items: items
			});
			//强制更新
			this.$forceUpdate();
		},
        redioChange: function (e) {
            console.log(e);
            this.setData({
                classId: e.detail.value,
                imgList: [],
                videoSrc: ''
            });
        },

        radioClick: function (e) {
            let classType = e.currentTarget.dataset.classtype;
            this.setData({
                classType: classType
            });
        },

        /**
         * 选择视频
         */
        myChooseVideo: function (e) {
            let that = this;
            console.log(e);
            uni.chooseVideo({
                sourceType: ['album'],
                compressed: false,
                maxDuration: 180,
                success: (res) => {
                    console.log(res);
                    let { duration, width, height, size } = res;

                    if (res.size <= that.maxByteVideo) {
                        that.setData({
                            videoSrc: res.tempFilePath,
                            videoCount: 1 //description: `视频时长：${duration}s; 视频宽度：${width}px; 视频高度：${height}px; 视频大小：${size}B`,
                        });
                    } else {
                        uni.showToast({
                            title: '选择失败文件超出设定大小',
                            // 内容
                            icon: 'none' // 图标
                        });
                    }
                },
                fail(err) {
                	let errType = err.errMsg.includes("chooseImage:fail cancel") ? "取消选择" : "选择失败";
                	console.log(err);
                	if(err.errMsg === 'chooseImage:fail auth deny'){
                		uni.openSetting({
                			success(res) {
                			},
                		})
                	}
                	
                  },
                complete(res) {
                },
            });
        },

        myDelVideo: function () {
            this.setData({
                videoSrc: '',
                videoCount: 0 //description: `视频时长：${duration}s; 视频宽度：${width}px; 视频高度：${height}px; 视频大小：${size}B`,
            });
        },

        /**
         * 选择图片
         */
        myChooseImage() {
            let that = this; //剩余可上传数量

            let surCount = that.uploadCount - that.uploadedQuantity;

            if (surCount <= 9) {
                that.setData({
                    optionCount: surCount
                });
            }

            uni.chooseImage({
                count: that.optionCount - that.imgList.length,
                //默认9
                //sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
                //sizeType: ['original'],
                sourceType: ['album'],
                //从相册选择
                success: (res) => {
                    console.log(res);
                    let files = res.tempFiles;
                    let files_eff = [];
                    let count = 0;

                    for (let i = 0; i < files.length; i++) {
                        if (files[i].size <= that.maxByte) {
                            //上传的大小
                            files_eff.push(files[i]);
                        } else {
                            count++;
                        }
                    }

                    console.log(res);

                    if (that.imgList.length != 0) {
                        that.setData({
                            imgList: that.imgList.concat(files_eff)
                        });
                    } else {
                        that.setData({
                            imgList: files_eff
                        });
                    }

                    if (count > 0) {
                        uni.showModal({
                            title: '系统提示',
                            // 标题
                            content: '您有' + count + '张图片超出10M,已被系统自动过滤',
                            // 内容
                            showCancel: true,
                            confirmText: '确定',
                            // 确定按钮的文案，最多 4 个字符
                            cancelText: '取消',
                            // 取消按钮的文案，最多 4 个字符
                            success: (res) => {},
                            fail: (res) => {}
                        });
                    }
                },
                fail(err) {
                	let errType = err.errMsg.includes("chooseImage:fail cancel") ? "取消选择" : "选择失败";
                	console.log(err);
                	if(err.errMsg === 'chooseImage:fail auth deny'){
                		uni.openSetting({
                			success(res) {
                			},
                		})
                	}
                	
                  },
                  complete(res) {
                },
            });
        },

        myViewImage(e) {
            let that = this;
            uni.previewImage({
                urls: that.imgList,
                // 图片地址列表
                current: e.currentTarget.dataset.url,
                success: (res) => {},
                fail: (res) => {}
            });
        },

        myDelImg(e) {
            let that = this;
            uni.showModal({
                title: '提示',
                content: '确定删除素材吗？',
                cancelText: '取消',
                confirmText: '确定',
                success: (res) => {
                    if (res.confirm) {
                        for (let i = 0; i < that.imgList.length; i++) {
                            if (e.currentTarget.dataset.index == i) {
                                that.imgList.splice(i, 1);
                                break;
                            }
                        }

                        that.setData({
                            imgList: that.imgList
                        });
                    }
                }
            });
        },

        /**
         * 获取基础信息
         */
        getBasicsData: function () {
            let that = this;
            uni.showLoading({
                title: '加载中' // 内容
            });
            var params = {
                url: '/u/my/basics',
                method: 'GET',
                data: {
                },
                callBack: function (res) {
                    if (res.code == 200) {
                        uni.hideLoading();
                        that.setData({
                            access_token: res.data.access_token,
                            ritems: res.data.classify,
                            items: res.data.tags,
                            uploadCount: res.data.uploadCount,
                            uploadedQuantity: res.data.uploadedQuantity
                        }); //计算可上传数量
                        //剩余可上传数量

                        let surCount = that.uploadCount - that.uploadedQuantity;
                        console.log(surCount);

                        if (surCount <= 9) {
                            that.setData({
                                optionCount: surCount
                            });
                        }
						if(surCount <= 0){
							uni.showModal({
								title:'提示',
								content:'今日上传数量已达到'+that.uploadCount+'张，请明日在来',
								success(res) {
									uni.navigateBack({
									    success: function() {
									    }
									});
								}
							})
						}
						
						
                    }

                    uni.hideLoading();
                }
            };
            http.request(params);
        },

        uploadImg: function () {
            let that = this;

            if (that.imgList.length == 0) {
                uni.showToast({
                    title: '请选择上传的素材',
                    duration: 1500,
                    icon: 'none'
                });
                return false;
            }

            if (that.isUpload) {
                return;
            } //提交的数据

            let sData = that.submitData();

            if (!that.valiData()) {
                return;
            }

            that.setData({
                isUpload: true
            });
            var tempFilePaths = that.imgList;
            let u = 0;
            uni.showLoading({
                title: '正在上传...'
            });

            for (let f = 0; f < tempFilePaths.length; f++) {
                sData.status = 1;
				sData.classType = that.classType;
                console.log(tempFilePaths[f].path); //图片上传

                uni.uploadFile({
                    url: Config.domain + '/platform/saveWallpaper',
                    filePath: tempFilePaths[f].path,
                    name: 'file',
                    header: {
                        'Content-Type': 'multipart/form-data',
                        accept: 'application/json',
                        Authorization: uni.getStorageSync(Constants.USER_TOKEN_KEY)
                    },
                    formData: sData,
                    success: function (res) {
						console.log(res);
                        let rData = JSON.parse(res.data);
                        that.setData({
                            isUpload: false
                        });
                        
                        if (rData.code != 200) {
                            uni.showToast({
                                title: rData.msg,
                                icon: 'fail'
                            });
                            return;
                        }
                        
                        u++;
                        
                        if (u == tempFilePaths.length) {
                            uni.hideLoading();
                            uni.showToast({
                                title: '上传成功',
                                duration: 2000
                            });
                            setTimeout(() => {
                                uni.navigateBack({
                                    delta: 1,
                                    success: (res) => {
                                        console.log('跳转成功');
                                    }
                                });
                            }, 1000);
                        }
                    },
                    fail: function (res) {
                        console.log(res);
                        console.log('fail');
                    }
                });
            }
        },

        /**
         * 上传视频
         */
        uploadVideo: function () {
            let that = this;

            if (!that.videoSrc) {
                uni.showToast({
                    title: '请选择素材',
                    duration: 1500,
                    icon: 'none'
                });
                return;
            }

            if (that.isUpload) {
                console.log('正在上传，请稍后');
                return;
            } //提交的数据

            let sData = that.submitData();
            sData.status = 1;

            if (!that.valiData()) {
                return;
            }

            that.setData({
                isUpload: true
            });
            uni.showLoading({
                title: '正在上传...'
            });
            uni.uploadFile({
                url: Config.domain + '/platform/saveWallpaper',
                filePath: that.videoSrc,
                name: 'file',
                header: {
                    'Content-Type': 'multipart/form-data',
                    accept: 'application/json',
                    Authorization: uni.getStorageSync(Constants.USER_TOKEN_KEY)
                },
                formData: sData,
                success: function (res) {
					console.log(res);
                    let rData = JSON.parse(res.data);
                    that.setData({
                        isUpload: false
                    });
                    uni.hideLoading();

                    if (rData.code != 200) {
                        uni.showToast({
                            title: '上传失败',
                            icon: 'fail'
                        });
                        return;
                    }

                    uni.showToast({
                        title: '上传成功',
                        // 内容
                        duration: 2000,
                        success: (res) => {
                            uni.navigateBack({
                                delta: 1,
                                success: (res) => {
                                    console.log('跳转成功');
                                }
                            });
                        },
                        fail: (res) => {}
                    }); 
                },
                fail: function (res) {
                    console.log(res);
                    console.log('fail');
                }
            });
        },

        /**
         * 提交数据
         */
        submitData: function () {
            let that = this;
            let d = that;
            let tags = '';
			let tagsIds = '';

            for (let i = 0; i < d.items.length; i++) {
                if (d.items[i].checked) {
                    if (tags == '') {
                        tags =  d.items[i].label;
						tagsIds = d.items[i].id;
                    } else {
                        tags += ',' + d.items[i].label;
						tagsIds += ','+ d.items[i].id;
                    }
                }
            }

            that.setData({
                tags: tags,
				tagsIds:tagsIds
            });
            let data = {
                classId: d.classId,
                tags: tags,
				tagsIds:tagsIds,
                classType: d.classType
            };
            return data;
        },

        /**
         * 验证数据
         */
        valiData: function () {
            let that = this;

            if (that.classId == '') {
                uni.showToast({
                    title: '请选择素材类型',
                    duration: 1500,
                    icon: 'none'
                });
                return false;
            } 
			
			console.log(that.tags);
			if(that.tags == ''){
              uni.showToast({
                title: "请选择标签",
                duration: 1500,
                icon:'none'
              });
              return false;
            }

            return true;
        }
    }


};
</script>
<style>
@import './upload.css';
</style>
